/*
 * FixedQueryArea.js - 通用查询区组件
 * 文档保存目录：/e:/DEV_VISION/frontend/static/js/FixedQueryArea.js
 *
 * 功能说明：
 *   1. 动态渲染查询区表单，支持文本、下拉等控件，全部配置驱动
 *   2. 查询和清除按钮自适应排列，所有控件与按钮同一行，自动换行
 *   3. 只负责参数收集和事件触发，结果展示和导出由业务模块自定义
 *   4. 兼容Bootstrap全局样式，无需自定义CSS
 *
 * 使用方法：
 *   1. 页面预留 <div id="fixedQueryArea"></div>
 *   2. import { renderFixedQueryArea } from './FixedQueryArea.js'
 *   3. renderFixedQueryArea(config, 'fixedQueryArea', onSearch, onClear)
 *      - config: 字段配置数组（如后端API返回的 fields）
 *      - onSearch: 查询按钮回调，参数为收集到的查询参数对象
 *      - onClear: 清除按钮回调（可选）
 */

function renderFixedQueryArea(
  config,
  containerId,
  onSearch,
  onClear,
  showColumnConfig = true,
  customButtons = []
) {
  const area = document.getElementById(containerId);
  area.innerHTML = "";
  area.style.width = "100%";
  area.style.minWidth = "0";

  // 统一渲染为一行，超出自动换行
  const row = document.createElement("div");
  row.className = "d-flex flex-wrap align-items-center gap-2 mb-2";
  row.style.width = "100%";
  row.style.minWidth = "0";

  // 🔧 优化：根据字段类型和内容智能调整默认宽度
  const getOptimalWidth = (fieldCfg) => {
    // 🔧 优化：优先使用配置中的宽度设置
    if (fieldCfg.width && !isNaN(fieldCfg.width)) {
      return fieldCfg.width;
    }
    
    const displayName = fieldCfg.display_name || fieldCfg.field;
    const fieldName = fieldCfg.field;
    
    // 根据字段名和显示名智能设置宽度
    switch(fieldCfg.input_type || fieldCfg.type) {
      case 'select':
      case 'dropdown':
        // 下拉框根据选项内容调整宽度
        if (fieldName === 'gender') return 80;  // 性别：男/女
        if (fieldName === 'grade') return 90;   // 年级：一年级/二年级等
        if (fieldName === 'school') return 140; // 学校名较长
        if (fieldName === 'data_year') return 100; // 年份
        return Math.max(90, Math.min(displayName.length * 10 + 30, 140));
        
      case 'text':
        // 文本输入框根据字段内容调整
        if (fieldName === 'name') return 80;        // 姓名
        if (fieldName === 'class_name') return 70;  // 班级
        if (fieldName === 'education_id') return 120; // 教育ID号
        if (fieldName === 'id_card') return 140;    // 身份证号
        if (fieldName === 'phone') return 120;      // 电话
        if (fieldName === 'parent_phone') return 120; // 家长电话
        if (displayName.length <= 4) return 80;     // 短字段
        if (displayName.length <= 8) return 100;    // 中等字段
        return 120; // 长字段
        
      case 'number':
        return 80; // 数字字段较窄
        
      case 'date':
        return 110; // 日期字段
        
      default:
        // 根据显示名长度智能调整
        if (displayName.length <= 4) return 80;
        if (displayName.length <= 8) return 100;
        return Math.min(displayName.length * 10 + 20, 120);
    }
  };

  // 渲染所有输入框
  config.forEach((fieldCfg) => {
    let widget;
    if (
      fieldCfg.input_type === "select" ||
      fieldCfg.options_source ||
      fieldCfg.type === "dropdown"
    ) {
      widget = document.createElement("select");
      widget.name = fieldCfg.field;
      widget.className = "form-select form-select-sm";
      const emptyOpt = document.createElement("option");
      emptyOpt.value = "";
      emptyOpt.textContent = fieldCfg.display_name || fieldCfg.field;
      widget.appendChild(emptyOpt);
      (fieldCfg.options || []).forEach((opt) => {
        const option = document.createElement("option");
        option.value = opt.value || opt;
        option.textContent = opt.label || opt;
        widget.appendChild(option);
      });
      if (fieldCfg.options_source) {
        fetch(`/api/config/options/${fieldCfg.options_source}`)
          .then((resp) => resp.json())
          .then((result) => {
            if (result.success && Array.isArray(result.options)) {
              result.options.forEach((opt) => {
                const option = document.createElement("option");
                option.value = opt.value || opt;
                option.textContent = opt.label || opt;
                widget.appendChild(option);
              });
            }
          })
          .catch((e) => {
            console.warn(`选项加载失败: ${fieldCfg.options_source}`);
          });
      }
    } else {
      widget = document.createElement("input");
      widget.type = "text";
      widget.name = fieldCfg.field;
      widget.className = "form-control form-control-sm";
      widget.placeholder = fieldCfg.display_name || fieldCfg.field;
    }
    
    // 🔧 优化：使用配置驱动的智能宽度设置
    const width = getOptimalWidth(fieldCfg);
    widget.style.width = width + "px";
    widget.style.minWidth = width + "px";
    // 优化wrapper，保证横向排列和自动换行
    const wrapper = document.createElement("div");
    wrapper.className = "flex-shrink-0";
    wrapper.style.flex = "0 0 auto";
    wrapper.style.minWidth = "0";
    wrapper.style.marginBottom = "8px";
    wrapper.appendChild(widget);
    row.appendChild(wrapper);
  });

  // 查询按钮
  const searchBtn = document.createElement("button");
  searchBtn.type = "submit";
  searchBtn.className = "btn btn-primary btn-sm";
  searchBtn.textContent = "查询";
  const searchWrapper = document.createElement("div");
  searchWrapper.className = "flex-shrink-0";
  searchWrapper.style.flex = "0 0 auto";
  searchWrapper.style.minWidth = "0";
  searchWrapper.appendChild(searchBtn);
  row.appendChild(searchWrapper);

  // 清除按钮
  const clearBtn = document.createElement("button");
  clearBtn.type = "button";
  clearBtn.className = "btn btn-warning btn-sm";
  clearBtn.textContent = "清除";
  clearBtn.style.marginLeft = "4px";
  const clearWrapper = document.createElement("div");
  clearWrapper.className = "flex-shrink-0";
  clearWrapper.style.flex = "0 0 auto";
  clearWrapper.style.minWidth = "0";
  clearWrapper.appendChild(clearBtn);
  row.appendChild(clearWrapper);

  // 自定义按钮（新增功能）
  customButtons.forEach(buttonConfig => {
    const customBtn = document.createElement("button");
    customBtn.type = "button";
    customBtn.className = buttonConfig.className || "btn btn-secondary btn-sm";
    customBtn.textContent = buttonConfig.text;
    customBtn.style.marginLeft = "4px";
    if (buttonConfig.onclick) {
      customBtn.addEventListener("click", buttonConfig.onclick);
    }
    const customWrapper = document.createElement("div");
    customWrapper.className = "flex-shrink-0";
    customWrapper.style.flex = "0 0 auto";
    customWrapper.style.minWidth = "0";
    customWrapper.appendChild(customBtn);
    row.appendChild(customWrapper);
  });

  // 列配置按钮（可选）
  if (showColumnConfig) {
    const columnConfigBtnWrapper = document.createElement("div");
    columnConfigBtnWrapper.className = "flex-shrink-0";
    columnConfigBtnWrapper.innerHTML = `
      <div class="btn-group ms-2 flex-shrink-0" style="align-self: flex-start; min-width: 57px">
        <button class="btn btn-secondary btn-sm dropdown-toggle" type="button" id="columnConfigBtn" data-bs-toggle="dropdown" aria-expanded="false">列配置</button>
        <ul class="dropdown-menu" id="columnConfigDropdown" style="max-height: 400px; overflow-y: auto; min-width: 320px">
          <li id="columnLoadingText">正在加载配置...</li>
        </ul>
      </div>
    `;
    row.appendChild(columnConfigBtnWrapper);
    
    // 加载列配置
    loadColumnConfig();
  }

  // 事件绑定
  const form = document.createElement("form");
  form.style.display = "block";
  form.style.margin = "0";
  form.style.padding = "0";
  form.style.width = "100%";
  form.appendChild(row);

  form.addEventListener("submit", function (e) {
    e.preventDefault();
    const params = {};
    config.forEach((fieldCfg) => {
      const value = form.elements[fieldCfg.field]?.value?.trim();
      if (value) params[fieldCfg.field] = value;
    });
    onSearch(params);
  });

  clearBtn.addEventListener("click", function () {
    config.forEach((fieldCfg) => {
      if (form.elements[fieldCfg.field])
        form.elements[fieldCfg.field].value = "";
    });
    if (typeof onClear === "function") onClear();
  });

  area.appendChild(form);
}

/**
 * 加载列配置
 */
async function loadColumnConfig() {
  try {
    const response = await fetch('/api/config/default-columns');
    const result = await response.json();
    
    if (result.success) {
      renderColumnConfig(result.config);
    } else {
      console.error('列配置加载失败:', result.error);
      renderColumnConfigError();
    }
  } catch (error) {
    console.error('列配置加载失败:', error);
    renderColumnConfigError();
  }
}

/**
 * 渲染列配置
 */
function renderColumnConfig(config) {
  const dropdown = document.getElementById('columnConfigDropdown');
  if (!dropdown) return;
  
  dropdown.innerHTML = '';
  
  // 添加全选功能
  const selectAllItem = document.createElement('li');
  selectAllItem.innerHTML = `
    <div class="dropdown-item">
      <input type="checkbox" id="selectAllColumns" class="form-check-input me-2">
      <label for="selectAllColumns" class="form-check-label">全选</label>
    </div>
  `;
  dropdown.appendChild(selectAllItem);
  
  // 添加分隔线
  const divider = document.createElement('li');
  divider.innerHTML = '<hr class="dropdown-divider">';
  dropdown.appendChild(divider);
  
  // 🔧 修正：兼容后端返回的OrderedDict格式，确保分组顺序正确
  const columnGroups = config.column_groups || {};
  const fieldDisplayMapping = config.field_display_mapping || {};
  const defaultSelected = config.default_selected || [];
  const alwaysVisible = config.always_visible || [];
  
  // 计算默认选中的字段（包括always_visible和default_selected）
  const shouldBeSelected = new Set([...alwaysVisible, ...defaultSelected]);
  
  // 🔧 修复：按照priority排序分组，确保固定顺序
  let groupsArray;
  if (Array.isArray(columnGroups)) {
    groupsArray = columnGroups;
  } else {
    // 转换为数组并按priority排序
    groupsArray = Object.entries(columnGroups)
      .map(([key, config]) => ({ key, ...config }))
      .sort((a, b) => (a.priority || 999) - (b.priority || 999));
  }
  
  groupsArray.forEach((groupItem, index) => {
    let groupKey, groupConfig;
    
    if (Array.isArray(columnGroups)) {
      // 如果是list格式
      groupKey = groupItem.key;
      groupConfig = groupItem;
    } else {
      // 如果是排序后的数组格式
      groupKey = groupItem.key;
      groupConfig = groupItem;
    }
    
    // 组标题（可折叠）
    const groupHeader = document.createElement('li');
    groupHeader.innerHTML = `
      <div class="dropdown-item d-flex align-items-center group-header" style="cursor: pointer;" data-group="${groupKey}">
        <i class="bi bi-chevron-right me-2"></i>
        <strong>${groupConfig.display}</strong>
      </div>
    `;
    dropdown.appendChild(groupHeader);
    
    // 组内字段容器
    const groupFieldsContainer = document.createElement('ul');
    groupFieldsContainer.className = `group-fields-${groupKey}`;
    groupFieldsContainer.style.display = 'none';
    groupFieldsContainer.style.listStyle = 'none';
    groupFieldsContainer.style.paddingLeft = '20px';
    
    // 组内字段
    const groupFields = groupConfig.fields || [];
    groupFields.forEach(fieldName => {
      const fieldItem = document.createElement('li');
      const displayName = fieldDisplayMapping[fieldName] || fieldName;
      const isSelected = shouldBeSelected.has(fieldName);
      
      fieldItem.innerHTML = `
        <div class="dropdown-item">
          <input type="checkbox" id="col_${fieldName}" class="form-check-input me-2 column-checkbox" value="${fieldName}" ${isSelected ? 'checked' : ''}>
          <label for="col_${fieldName}" class="form-check-label">${displayName}</label>
        </div>
      `;
      groupFieldsContainer.appendChild(fieldItem);
    });
    
    dropdown.appendChild(groupFieldsContainer);
    
    // 添加组间分隔线
    const groupDivider = document.createElement('li');
    groupDivider.innerHTML = '<hr class="dropdown-divider">';
    dropdown.appendChild(groupDivider);
  });
  
  // 绑定事件
  bindColumnConfigEvents();
  
  // 初始化全选状态
  updateSelectAllState();
}

/**
 * 渲染列配置错误
 */
function renderColumnConfigError() {
  const dropdown = document.getElementById('columnConfigDropdown');
  if (!dropdown) return;
  
  dropdown.innerHTML = `
    <li>
      <div class="dropdown-item text-danger">
        <i class="bi bi-exclamation-triangle me-2"></i>
        配置加载失败
      </div>
    </li>
  `;
}

/**
 * 绑定列配置事件
 */
function bindColumnConfigEvents() {
  // 全选功能
  const selectAllCheckbox = document.getElementById('selectAllColumns');
  if (selectAllCheckbox) {
    selectAllCheckbox.addEventListener('change', function() {
      const columnCheckboxes = document.querySelectorAll('.column-checkbox');
      columnCheckboxes.forEach(checkbox => {
        checkbox.checked = selectAllCheckbox.checked;
      });
      updateTableDisplay();
    });
  }
  
  // 单个复选框变化
  const columnCheckboxes = document.querySelectorAll('.column-checkbox');
  columnCheckboxes.forEach(checkbox => {
    checkbox.addEventListener('change', function() {
      updateTableDisplay();
      updateSelectAllState();
    });
  });
  
  // 🔧 修正：组折叠功能，绑定在group-header上，阻止下拉菜单关闭
  const groupHeaders = document.querySelectorAll('.group-header');
  groupHeaders.forEach(header => {
    header.addEventListener('click', function(e) {
      e.preventDefault();
      e.stopPropagation();
      const groupKey = this.dataset.group;
      const icon = this.querySelector('i');
      const container = document.querySelector(`.group-fields-${groupKey}`);
      
      if (!container) return;
      
      if (container.style.display === 'none') {
        // 展开：显示字段，改变图标
        container.style.display = 'block';
        icon.classList.remove('bi-chevron-right');
        icon.classList.add('bi-chevron-down');
      } else {
        // 折叠：隐藏字段，改变图标
        container.style.display = 'none';
        icon.classList.remove('bi-chevron-down');
        icon.classList.add('bi-chevron-right');
      }
    });
  });
}

/**
 * 更新表格显示
 */
function updateTableDisplay() {
  // 🔧 修复：列配置变化时重新获取数据，确保数据与列配置同步
  if (window.fetchData && typeof window.fetchData === 'function') {
    // 重新获取数据，确保后端返回正确的列数据
    window.fetchData();
  } else if (window.renderTable && typeof window.renderTable === 'function') {
    // 备用方案：如果fetchData不可用，只重新渲染表格
    window.renderTable(window.latestData || []);
  }
}

/**
 * 更新全选状态
 */
function updateSelectAllState() {
  const selectAllCheckbox = document.getElementById('selectAllColumns');
  const columnCheckboxes = document.querySelectorAll('.column-checkbox');
  
  if (selectAllCheckbox && columnCheckboxes.length > 0) {
    const checkedCount = Array.from(columnCheckboxes).filter(cb => cb.checked).length;
    selectAllCheckbox.checked = checkedCount === columnCheckboxes.length;
    selectAllCheckbox.indeterminate = checkedCount > 0 && checkedCount < columnCheckboxes.length;
  }
}

/**
 * 获取选中的列
 */
function getSelectedColumns() {
  const selected = [];
  const checkboxes = document.querySelectorAll('.column-checkbox:checked');
  checkboxes.forEach(cb => {
    selected.push(cb.value);
  });
  return selected;
}

window.renderFixedQueryArea = renderFixedQueryArea;
